var util = require('../../../../utils/util.js');
var api = require('../../../../config/api.js');
var Map = require("../../../../utils/map.js");

// 获取地图的返回信息
const chooseLocation = requirePlugin('chooseLocation');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        region: [],
        isClearShow: false,
        hasStorefront: true,
        showPhoneValid: false,
        userPhone: "",
        location: {
            latitude: 0,
            longitude: 0
        },
        mapName: "",
        mapDetail: "",
        disabled: false,
        findMerchantCityInfoList: [],
	},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.findMerchantCityInfoListData();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const location = chooseLocation.getLocation();
        if(location){
            let mapName = location.province + location.city + location.district;
            
            console.log("123");
            if(!mapName){
                mapName = location.address.split(location.name)[0] || ""
            }
            const mapDetail = location.address.split(location.district)[1] + location.name;
            this.setData({
                location,
                mapName: mapName || "",
                mapDetail: mapDetail || ""
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        chooseLocation.setLocation(null);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 地图事件
    toMap(){
        Map.getAddress(this.data.location);
    },
    // 手机事件 开始
    clearHide: function(e){
        const value = this.data.userPhone;
        if (!(/^1[3456789]\d{9}$/.test(value))) {
            this.setData({
                showPhoneValid: true,
            });
        } else {
            this.setData({
                showPhoneValid: false,
            });
            
        }
        this.setData({
            isClearShow: false,
        });
    },
    clearShow: function(e){
        this.setData({
            showPhoneValid: false,
            isClearShow: true,
        })
    },
    clearPhone: function(e){
        this.setData({
            userPhone: ""
        })
    },
    phoneInput: function(e){
        this.setData({
            userPhone: e.detail.value
        })
    },
    // 手机事件 结束
    // 后台请求
    applyMember(data) {
        wx.showLoading({
            title: "正在提交中",
            icon: "none",
        });
        this.setData({
            disabled: true
        })
        util.request(api.wholesaler.wholesalerPost, data, "POST")
            .then((res) => {
                console.log("ress", res);
                wx.hideLoading();
                this.setData({
                    disabled: false
                })
                // wx.showToast({
                //     title: res.message,
                //     icon: "none"
                // })
                wx.redirectTo({
                    url: "/pages/wholesalers/application/application-result/application-result?status=1",
                });
            })
            .catch((err) => {
                console.log("err", err);
                wx.hideLoading();
                this.setData({
                    disabled: false
                })
                wx.showToast({
                    title: err.message,
                    icon: "none",
                });
            });
    },
    // 提交表单
    formSubmit: function (e) {
        const result = this.validForm(e.detail.value);
        if (result) {
            // 验证成功
            const data = this.getParams(e.detail.value);
            console.table(data);
            this.applyMember(data);
        }
    },
    radioChange: function(e){
        this.setData({
            isSupportFreeze: e.detail.value == 1 ? true : false
        })
    },
    // 表单验证
    validForm(values){
        let keys = [];//必填选项
        const { location } = this.data;
        keys = ["userName", "userPhone", "addressDesc", "wholesalerName"]; //必填选项

        const result = keys.every((item) => values[item]);
        if (!result) {
            wx.showToast({
                title: "还有选项没填哦",
                icon: "none",
            });
            return false;
        }
        if(location.latitude == 0){
            wx.showToast({
                title: "所在位置还没选哦",
                icon: "none"
            })
            return false;
        }
        return true;
    },
    // 参数处理
    getParams(values){
        const { location, mapName, mapDetail, findMerchantCityInfoList} = this.data;
        const userInfo = wx.getStorageSync("userInfo");
        const cityId = findMerchantCityInfoList.find(
            (item) => item.cityName == this.data.location.city
        ) || {id: 0};
        let defaultData = {
            "addressDesc": "",
            "isSupportFreeze": false,
            "lat": location.latitude,
            "lon": location.longitude,
            "memberId": userInfo.id || 0,
            "cityId": cityId.id || 0,
            "status": 0,
            "userPhone": "",
            "wholesalerName":""
        };
        values.addressDesc = mapName + mapDetail;
        values.isSupportFreeze = values.isSupportFreeze == 1 ? true : false;
        return Object.assign(defaultData, values)
    },
    findMerchantCityInfoListData() {
        util.request(
            api.surroundings.findMerchantCityInfoList,
            {},
            "POST"
        ).then((res) => {
            console.log("res");
            this.setData({
                findMerchantCityInfoList: res.result,
            });
        });
    }
});
